import threading
from pynput import mouse

class MouseClickTracker:
    """鼠标点击监听器 - 修复版"""
    def __init__(self, callback):
        self.callback = callback
        self.listener = None
        self.running = False
        self.lock = threading.Lock()  # 添加线程锁
        
    def on_click(self, x, y, button, pressed):
        """鼠标点击事件处理 - 修复版"""
        if pressed and button == mouse.Button.left:
            # 在新线程中执行回调，避免阻塞监听器
            threading.Thread(target=self.callback, args=(x, y), daemon=True).start()
            return True  # 继续监听，不停止
            
    def start_listening(self):
        """开始监听鼠标点击 - 修复版"""
        with self.lock:
            if not self.running:
                self.running = True
                self.listener = mouse.Listener(on_click=self.on_click)
                self.listener.start()
                print("鼠标点击监听已启动")
                
    def stop_listening(self):
        """停止监听鼠标点击 - 修复版"""
        with self.lock:
            if self.running and self.listener:
                self.running = False
                self.listener.stop()
                self.listener = None
                print("鼠标点击监听已停止")